package com.ruoyi.project.system.controller

import com.ruoyi.common.constant.UserConstants
import com.ruoyi.common.utils.SecurityUtils
import com.ruoyi.common.utils.StringUtils
import com.ruoyi.common.utils.file.FileUploadUtils
import com.ruoyi.common.utils.file.MimeTypeUtils
import com.ruoyi.framework.aspectj.lang.annotation.Log
import com.ruoyi.framework.aspectj.lang.enums.BusinessType
import com.ruoyi.framework.config.RuoYiConfig
import com.ruoyi.framework.security.service.TokenService
import com.ruoyi.framework.web.controller.BaseController
import com.ruoyi.framework.web.domain.AjaxResult
import com.ruoyi.project.system.domain.SysUser
import com.ruoyi.project.system.service.ISysUserService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.*
import org.springframework.web.multipart.MultipartFile

/**
 * 个人信息 业务处理
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/user/profile")
open class SysProfileController : BaseController() {
    @Autowired
    private val userService: ISysUserService? = null

    @Autowired
    private val tokenService: TokenService? = null

    /**
     * 个人信息
     */
    @GetMapping
    fun profile(): AjaxResult {
        val loginUser = loginUser
        val user = loginUser.user
        val ajax: AjaxResult = AjaxResult.Companion.success(user)
        ajax["roleGroup"] = userService!!.selectUserRoleGroup(loginUser.username)
        ajax["postGroup"] = userService.selectUserPostGroup(loginUser.username)
        return ajax
    }

    /**
     * 修改用户
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping
    fun updateProfile(@RequestBody user: SysUser): AjaxResult {
        val loginUser = loginUser
        val sysUser = loginUser.user!!
        user.userName = sysUser.userName
        // 更新缓存用户信息
        when {
            StringUtils.isNotEmpty(user.phonenumber) && UserConstants.NOT_UNIQUE == userService!!.checkPhoneUnique(user) -> {
                return AjaxResult.error("修改用户'" + user.userName + "'失败，手机号码已存在")
            }
            StringUtils.isNotEmpty(user.email) && UserConstants.NOT_UNIQUE == userService!!.checkEmailUnique(user) -> {
                return AjaxResult.error("修改用户'" + user.userName + "'失败，邮箱账号已存在")
            }
            else -> {
                user.userId = sysUser.userId
                user.password = null
                user.avatar = null
                user.deptId = null
                return when {
                    userService!!.updateUserProfile(user) > 0 -> {
                        // 更新缓存用户信息
                        sysUser.nickName = user.nickName
                        sysUser.phonenumber = user.phonenumber
                        sysUser.email = user.email
                        sysUser.sex = user.sex
                        tokenService!!.setLoginUser(loginUser)
                        AjaxResult.success()
                    }
                    else -> AjaxResult.error("修改个人信息异常，请联系管理员")
                }
            }
        }
    }

    /**
     * 重置密码
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping("/updatePwd")
    fun updatePwd(oldPassword: String?, newPassword: String?): AjaxResult {
        val loginUser = loginUser
        val userName = loginUser.username
        val password = loginUser.password
        return when {
            !SecurityUtils.matchesPassword(oldPassword, password) -> {
                AjaxResult.error("修改密码失败，旧密码错误")
            }
            SecurityUtils.matchesPassword(newPassword, password) -> {
                AjaxResult.error("新密码不能与旧密码相同")
            }
            userService!!.resetUserPwd(userName, SecurityUtils.encryptPassword(newPassword)) > 0 -> {
                // 更新缓存用户密码
                loginUser.user!!.password = SecurityUtils.encryptPassword(newPassword)
                tokenService!!.setLoginUser(loginUser)
                AjaxResult.success()
            }
            else -> AjaxResult.error("修改密码异常，请联系管理员")
        }
    }

    /**
     * 头像上传
     */
    @Log(title = "用户头像", businessType = BusinessType.UPDATE)
    @PostMapping("/avatar")
    @Throws(Exception::class)
    fun avatar(@RequestParam("avatarfile") file: MultipartFile): AjaxResult {
        if (!file.isEmpty) {
            val loginUser = loginUser
            val avatar =
                FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file, MimeTypeUtils.IMAGE_EXTENSION)
            when {
                userService!!.updateUserAvatar(loginUser.username, avatar) -> {
                    val ajax: AjaxResult = AjaxResult.success()
                    ajax["imgUrl"] = avatar
                    // 更新缓存用户头像
                    loginUser.user!!.avatar = avatar
                    tokenService!!.setLoginUser(loginUser)
                    return ajax
                }
            }
        }
        return AjaxResult.error("上传图片异常，请联系管理员")
    }
}
